<?php
namespace Org\Util;

class PDOFactory{
	
	public static function GetPDO($host,$dbname,$user,$pass){
		$strKey=md5(serialize(array($host,$dbname,$user,$pass)));
		if(!isset($GLOBALS[$strKey])){
			$GLOBALS[$strKey]=new \PDO("mysql:host=".$host.";dbname=".$dbname,$user,$pass);
		}
		return $GLOBALS[$strKey];
	}
}

class Mysql{
	protected $mysql;
	function __construct(){
		
		$host	=	C('db_host');
		$dbName	=	C('db_name');
		$user	=	C('db_user');
		$pass	=	C('db_pass');
		
		$this->mysql=PDOFactory::GetPDO($host,$dbName,$user,$pass);
		if(!$this->mysql) echo "mysql connect is faild!<br>";
		$this->mysql->query("set names utf8");
	}
	//sql信息写入
	function insertItem($tablename,$insertItem){
		$keys = ""; $values = "";
		foreach($insertItem as $key=>$value){
			$keys .=$key.","; $values .= $value.",";
		}
		$keys = substr($keys,0,strlen($keys)-1);
		$values = substr($values,0,strlen($values)-1);
		
		$insert = $this->mysql->prepare("insert into $tablename($keys) values ($values)");
		$status = $insert->execute();
		
		//return "insert into $tablename($keys) values ($values)";
		return $status;
	}
	//sql信息获取
	function selectItem($tablename,$whereItem = null,$keysItem = null,$limitItem = null){
		if(isset($whereItem)){
			$where = "";
			foreach($whereItem as $key => $value){
				$where .= $key." = ".$value." and ";
			}
			$where = substr($where, 0 ,strlen($where)-4);
			$where = "where ".$where;
		}else{
			$where = "";
		}
		
		if(isset($keysItem)){
			$keys = "";
			foreach($keysItem as $value){
				$keys .= $value.",";
			}
			$keys = substr($keys, 0, strlen($keys)-1);
		}else{
			$keys="*";
		}
		
		if(isset($limitItem)){
			$limit = "limit $limitItem[0],$limitItem[1]";
		}else{
			$limit = "";
		}
		
		$select = $this->mysql->prepare("select $keys from $tablename $where $limit");
		$select->execute();
		
		$arResult = array();
		while($row = $select->fetch(\PDO::FETCH_ASSOC)){
			array_push($arResult, $row);
		}
		
		return $arResult;
	}
	//sql信息更改
	function updateItem($tablename,$setItem,$whereItem){
		//set字符串格式化
		$set = "set ";
		foreach($setItem as $key => $value){
			$set .= $key." = ".$value." ,";
		}
		$set = substr($set,0,strlen($set)-1);
		
		//where字符串格式化
		$where = "where ";
		foreach($whereItem as $key => $value){
			$where .= $key." = ".$value." and ";
		}
		$where = substr($where, 0 ,strlen($where)-4);
		
		$update = $this->mysql->prepare("update $tablename $set $where");
		$status = $update->execute();
		
		return $status;
	}
	
	//获取最大ID
	function getMaxId(){
		$select = $this->mysql->prepare("select max(workerid) workerid from iry_worker_info");
		$select->execute();
		
		$row=$select->fetch(\PDO::FETCH_ASSOC);
		return $row['workerid'];
	}
	
	function __destruct(){
		$this->mysql=NULL;
	}
}
?>